import {Component, OnInit, Input, EventEmitter, Output, ChangeDetectorRef, PipeTransform, Pipe} from "@angular/core";
import { IonicPage, NavController, Navbar, NavParams } from "ionic-angular";
import { StepPathComponentProperty } from "../step-path/step-path.component";
import { DistrictService } from "../../models/services/district.service";
import { BillDto } from "../../../shared/models/dto/bill.dto";
import { WorkOrderDto } from "../../../shared/models/dto/work-orders.dto";
import { CurdService } from "../../../shared/models/services/curd.service";
import { UtilsService } from "../../../shared/services/utils.services";
import { WorkOrderType, WorkOrderStatus } from "../../models/transform/work-order";
import { ChargeFlowPath } from "./charge-flow-path";
import { PowerCutPathData } from "./power-cut-path-data";
import { RecoverPathData } from "./recover-path-data";
import { ComponentUtilService } from "../component.util.service";
import { Observable } from "rxjs";
// import { FormatTimePipe } from "../../../modules/charge/pages/charge-list/charge-list.page";

export interface ChargeFlowPathInterFace {
  name?: string;
  description?: string;
  status?: number;
  type?: WorkOrderType;
  month?: string;
  time?: string;
  frequency?: number;
  attachment?: string;
  totalFee?: number;
  stepProp: StepPathComponentProperty;
}

@Component({
    selector: 'charge-flow-path-component',
    templateUrl: './charge-flow-path.component.html',
})

export class ChargeFlowPathComponent {
    @Input('Data') flowPathData: {
      chargeDetailId: "",
      userId: ""
    };
    // tslint:disable-next-line:no-input-rename
    // @Input('Data') flowPathData: any;
    chargeDetailId: string;
    userNo: string;
    show: boolean = false;
    chargeFlowPathArray: Array<ChargeFlowPathInterFace> = [];
    powerCutOrder: any;
    recoverOrder: any;
    billData: any;
    countdown: any;
    recordDate: any;
    overTime: boolean = false;


    powerRecover: any = WorkOrderType.POWERRECOVERY;
    powerCut: any = WorkOrderType.POWERCUT;

    constructor(
      public districtService: DistrictService,
      public ref: ChangeDetectorRef,
      public navCtrl: NavController,
      public curdService: CurdService,
      public utilsService: UtilsService,
      public componentUtilService: ComponentUtilService
        ) {
        // TODO
    }

    update() {
      this.chargeFlowPathArray = [];
      this.getOrder();
    }

    // ngOnInit(): void {
    //   this.getOrder();
    // }

    getAllChargeDetailIdAndUserId() {
      let chargeDetailIds: Array<string> = this.flowPathData.chargeDetailId.split(",");
      return chargeDetailIds.map((id) => {
        return {
          userId: this.flowPathData.userId,
          chargeDetailId: id
        };
      });
    }

    getAllBills() {
      return Observable.fromPromise(this.curdService.fetchByCondition(BillDto, {
          or: this.getAllChargeDetailIdAndUserId()
        })).map((sqlResults) => {
          let sqlResultsArray: Array<object>;
          sqlResultsArray = Array.from(sqlResults["results"]);
          sqlResultsArray = sqlResultsArray.sort((sqlResultA, sqlResultB) => {
            return sqlResultB["billDate"] - sqlResultA["billDate"];
          });
          return sqlResultsArray;
        });
    }

    getOrder() {
      Observable.fromPromise(this.curdService.fetchByCondition(WorkOrderDto, {
        and: {
          userId: this.flowPathData.userId,
          chargeDetailId: this.flowPathData.chargeDetailId
        }
        // in: {
        //   workOrderStatus: [WorkOrderStatus.TO_BE_SUBMIT, WorkOrderStatus.TO_BE_APPROVED, WorkOrderStatus.APPROVED,
        //     WorkOrderStatus.REJECTED, WorkOrderStatus.EXECUTED]
        // }
      })).map((orderResults: any) => {
        let resultArray = Array.from(orderResults["results"]);
        // resultArray = resultArray.filter((item) => {
          // powerCut
          // if (item["workOrderStatus"] === WorkOrderStatus.EXECUTED &&
          //   item["type"] === WorkOrderType.POWERRECOVERY) {
          //   return false;
          // } else {
          //   return true;
          // }
          // TODO isSettle
        // });
        return resultArray;
      }).subscribe((orderResults: any) => {
        switch (orderResults.length) {
          case 0 : this.unSubmitPowerCutApply(); break; // 未提交停电申请记录
          case 1 : this.hadSubmitPowerCutApply(orderResults); break; // 已提交停电申请记录
          case 2 : this.hadSubmitRecoverApply(orderResults); break; // 已提交复电申请
          default : this.utilsService.tip("工单查询出错！"); break;
        }
      });
    }

    // 还没有提交任何一条工单情况下的催费状态
    unSubmitPowerCutApply() {
      let recentBill: {
        chargeLevel: number,
      } ;
      this.getAllBills().subscribe((billOrderArray: Array<{
        chargeLevel: number,
      }>) => {
        if (billOrderArray.length < 1) {
          this.utilsService.tip("用户的欠费记录和缴费记录的查询出错！");
          return ;
        }
        recentBill = billOrderArray[0];
        // 判断当前是处于第几级的催费状态下
        switch (recentBill.chargeLevel) {
          case -1: this.startThreeCharge(recentBill); break;
          case 3: this.startThreeCharge(recentBill); break;
          case 2: this.startTwoCharge(recentBill); break;
          case 1: this.startOneCharge(recentBill); break;
          default: break;
        }
      });
    }

    // 仅仅提交了停电申请情况下的催费状态
    hadSubmitPowerCutApply(orderResults: Array<{
      workOrderStatus: number,
      chargeDetailId: number
    }>) {
        // 先判断有无缴清费用
      let recentBill;
      this.getAllBills().subscribe((billOrderArray: Array<{
        chargeLevel: number,
      }>) => {
        if (billOrderArray.length < 1) {
          this.utilsService.tip("用户的欠费记录和缴费记录的查询出错！");
          return;
        }
        recentBill = billOrderArray[0];
        this.billData = billOrderArray[0];
        this.powerCutOrder = orderResults[0];
        // if (recentBill.isSettle) {
        //   let auditSubmitRecover = ChargeFlowPath.data.auditSubmitRecover;
        //   this.chargeFlowPathArray.push(auditSubmitRecover);
        //   let alreadyPay = ChargeFlowPath.data.alreadyPay;
        //   this.chargeFlowPathArray.push(alreadyPay);
        //   this.powerCutPath(orderResults[0]);
        // } else {
          // 从停电开始判断
        this.powerCutPath(orderResults[0]);
        // }
      });

    }
// 有复电工单
    hadSubmitRecoverApply(orderResults: Array<{
      workOrderStatus: number,
      type: number
    }>) {
        let recentOrder: any;
        let powerCutOrder: any;
        recentOrder = orderResults.filter((item) => {
          return item.type === WorkOrderType.POWERRECOVERY;
        });
        recentOrder = recentOrder[0];
        this.recoverOrder = recentOrder;
        for (let index = 0; index < RecoverPathData.data.length; index ++) {
          if (RecoverPathData.data[index]["status"] === recentOrder.workOrderStatus) {
            if (recentOrder.workOrderStatus === WorkOrderStatus.EXECUTED) {
              this.recordDate = recentOrder.recordDate;
            }
            this.chargeFlowPathArray.push(RecoverPathData.data[index]);
            if (++index <  RecoverPathData.data.length ) {
              for (let j = index; j < RecoverPathData.data.length; j ++) {
                // 移除审核不通过的情况
                if (this.chargeFlowPathArray.length > 0 && RecoverPathData.data[j]["status"] === WorkOrderStatus.REJECTED) {
                  continue;
                }
                this.chargeFlowPathArray.push(RecoverPathData.data[j]);
              }
            }
          }
        }
        let counter = this.utilsService.getCounter(recentOrder.payDate);
        this.overTime = counter.isOverTime;
        this.countdown = this.utilsService.productionCountdown(counter.counter);
        powerCutOrder = orderResults.filter((item) => {
          return item.type === WorkOrderType.POWERCUT;
        });
        this.powerCutOrder = powerCutOrder[0];
        this.hadSubmitPowerCutApply(powerCutOrder);
    }

    // 停电审核流程
    powerCutPath(recentOrder: {
      workOrderStatus: number
    }) {
      for (let index = 0; index < PowerCutPathData.data.length; index ++) {
        if (PowerCutPathData.data[index]["status"] === recentOrder.workOrderStatus) {
          let powerCutPathData = PowerCutPathData.data[index];
          powerCutPathData.totalFee = this.billData.totalFee;
          this.chargeFlowPathArray.push(powerCutPathData);
          if (++index <  PowerCutPathData.data.length ) {
            for (let j = index; j < PowerCutPathData.data.length; j ++) {
              // 移除审核不通过的情况
              if (this.chargeFlowPathArray.length > 0 && RecoverPathData.data[j]["status"] === WorkOrderStatus.REJECTED) {
                continue;
              }
              let powerCutPathUnData = PowerCutPathData.data[j];
              powerCutPathUnData.totalFee = this.billData.totalFee;
              this.chargeFlowPathArray.push(powerCutPathUnData);
            }
          }
        }
      }
      this.unSubmitPowerCutApply();
    }

    // 三级催费节点
    startThreeCharge(curBill) {
      let three = ChargeFlowPath.data.three;
      three.month = `${curBill['month']}月`;
      three.frequency = curBill["chargeTimesThree"];
      three.totalFee = curBill.totalFee;
      this.chargeFlowPathArray.push(three);
      this.startTwoCharge(curBill);
    }

    // 二级催费节点
    startTwoCharge(curBill) {
      this.billData = curBill;
      if (curBill.noticeUploadTime) {
        let twoNotice = ChargeFlowPath.data.twoNotice;
        twoNotice.totalFee = curBill.totalFee;
        twoNotice.month = `已粘贴${curBill['month']}月`;
        this.chargeFlowPathArray.push(twoNotice);
      }
      let two = ChargeFlowPath.data.two;
      two.month = `${curBill['month']}月`;
      two.frequency = curBill["chargeTimesTwo"];
      two.totalFee = curBill.totalFee;
      this.chargeFlowPathArray.push(two);
      this.startOneCharge(curBill);
    }

    // 一级催费节点
    startOneCharge(curBill) {
      let one = ChargeFlowPath.data.one;
      one.month = `${curBill['month']}月`;
      one.totalFee = curBill.totalFee;
      one.frequency = curBill["chargeTimesOne"];
      this.chargeFlowPathArray.push(one);
    }

    // productionCountdown(counter) {
    //   return Observable.timer(0, 1000 * 60)
    //     .take(counter)
    //     .map(() => {
    //       --counter;
    //       if (counter === 0) {
    //         // TODO
    //       }
    //       return counter;
    //     });
    // }

    jump(item) {
      // TODO
      switch (item.name) {
        case "alreadyPowerCut" :
          this.navCtrl.push("UploadingPowerFailureDetailPage",
            {workData: this.powerCutOrder});
          break;
        case "auditPowerCut" :
          this.navCtrl.push("StopPowerApplicationDetailPage",
            {userId: this.flowPathData.userId, chargeDetailId: this.flowPathData.chargeDetailId});
          break;
        case "toBeApproved" :
          this.navCtrl.push("StopPowerApplicationDetailPage",
            {userId: this.flowPathData.userId, chargeDetailId: this.flowPathData.chargeDetailId});
          break;
        case "alreadyRecover" :
          this.navCtrl.push("ImplementRecordDetailPage",
            {userId: this.flowPathData.userId, chargeDetailId: this.flowPathData.chargeDetailId});
          break;
        case "recoverToBeApproved" :
          this.navCtrl.push("ApplyResumptionDetailPage",
          {userId: this.flowPathData.userId, chargeDetailId: this.flowPathData.chargeDetailId});
          break;
        case "twoNotice" :
          this.navCtrl.push("UploadingNoticeDetailPage",
            {noticeTime: this.billData.noticeUploadTime, attachmentId: this.billData.attachmentIds});
          break;
        default : break;
      }
    }

}


@Pipe({
  name: 'timeDownCut'
})
export class TimeDownCutPipe implements PipeTransform {
  transform(value: number): string {
    const hour: number = Math.floor(value / 3600);
    return ('00' + hour).slice(-2) + ':' + ('00' + Math.floor((value - hour * 60 * 60) / 60 )).slice(-2);
  }
}
